package com.fayou.cloud.multipledatasourcemybatisplus.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

@Configuration
@ConfigurationProperties(prefix = "spring.")
@MapperScan(basePackages = "com.fayou.cloud.multipledatasourcemybatisplus.dao"/*, sqlSessionFactoryRef = "storageSqlSessionFactory",
        sqlSessionTemplateRef = "storageSqlSessionTemplate"*/)
public class DruidStorageConfig {
//    /**
//     * 多数据源时，第一个数据源指定Primary
//     */
    @Bean("dataSourceStorage")
//    @ConfigurationProperties("spring.datasource.druid.storage")
    public DataSource dataSourceStorage() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/seata_storage?serverTimezone=UTC&autoReconnect=true&failOverReadOnly=false&useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        //初始连接数(默认值0)
        dataSource.setInitialSize(8);
        //最小连接数(默认值0)
        dataSource.setMinIdle(8);
        //最大连接数(默认值8,注意"maxIdle"这个属性已经弃用)
        dataSource.setMaxActive(32);
        return dataSource;
    }

//    @Bean(name = "storageSqlSessionFactory")
//    public SqlSessionFactory setSqlSessionFactory(@Qualifier("dataSourceStorage") DataSource dataSource) throws Exception {
//        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
//        bean.setDataSource(dataSource);
//        return bean.getObject();
//    }
//
//    @Bean(name = "storageSqlSessionTemplate")
//    public SqlSessionTemplate SqlSessionTemplate1(
//            @Qualifier("storageSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
//        return new SqlSessionTemplate(sqlSessionFactory);
//    }
}
